package org.example.algorithm.linkedlist;

import java.util.HashMap;
import java.util.Map;

public class CopyRandomListSolution {

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Node cur = head;
        //赋值节点到原链表
        while (cur != null) {
            Node temp = cur.next;
            Node newNode = new Node(cur.val);
            cur.next = newNode;
            newNode.next = temp;
            cur = temp;
        }
        //遍历链表处理random引用
        cur = head;
        while (cur != null) {
            if (cur.random != null) {
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }
        //拆分链表
        cur = head;
        Node newHead = new Node(0);
        Node tail = newHead;
        while (cur != null) {
            tail.next = cur.next;
            tail = tail.next;
            cur.next = cur.next.next;
            cur = cur.next;
        }
        return newHead.next;
    }

    //使用hash表
    public Node copyRandomList2(Node head) {
        if (head == null) {
            return null;
        }
        Node newNode = new Node(0);
        Node tail = newNode;
        Node cur = head;
        Map<Node, Node> map = new HashMap<>();
        while (cur != null) {
            tail.next = new Node(cur.val);
            map.put(cur, tail.next);
            tail.next.random = cur.random;
            tail = tail.next;
            cur = cur.next;
        }
        cur = newNode.next;
        while (cur != null) {
            if (cur.random != null) {
                cur.random = map.get(cur.random);
            }
            cur = cur.next;
        }
        return newNode.next;
    }

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
}
